# -*- coding:utf-8 -*-
import json,time,operator
from conf import hosts

#将每台主机的配置信息存入redis
def pull_cofig_redis(redis_instance,monitor_groups):
    host_config_dic = {}
    #print monitor_groups
    for group in monitor_groups:
        #print group,
        for host in group.hosts:
            #print host,   
            if host not in host_config_dic:
                host_config_dic[host] = {}
            for s in group.services:
                host_config_dic[host][s.name]=[s.plugin_name,s.interval]
    
    for h,v in host_config_dic.items():
        client_config_key = "clientconfig::%s"%(h,)
        redis_instance.redis_conn.set(client_config_key,json.dumps(v))
        

def fetch_all_configs(monitor_groups):
    #取出每台主机所有配置信息
    host_config_dic={}
    for group in monitor_groups:
    #循环主机组里的每台机器
        for host in group.hosts:
            #给每台主机生成一个配置字典
            if host not in host_config_dic:
                host_config_dic[host]={}
            #循环服务组里要监控的服务
            for s in group.services:
                host_config_dic[host][s.name]=s

    for h,v in host_config_dic.items():
            print h,v
    return host_config_dic        
        
def data_process(main_ins):
    print '--going to handle monitor client data'
    #取出每台主机的配置信息
    all_host_configs = fetch_all_configs(hosts.monitor_groups)
    #循环每台主机的配置信息（ip,service）
    for ip , service_dic in all_host_configs.items():
        #循环每个服务的信息
        for service_name,service_instance in service_dic.items():
            #从redis取出客户端插件运行数据
            service_redis_key = 'ServiceData::%s::%s'% (ip,service_name)
            s_data = main_ins.redis_conn.get(service_redis_key)
            #判断从redis能否取出客户端插件运行数据
            if s_data:
                s_data = json.loads(s_data)
                print '###>',s_data
                time_stamp =  s_data['time_stamp']
                if time.time() - time_stamp  < service_instance.interval:#最新的有效数据
                    #判断插件是否正确执行,最新的有效数据
                    if s_data['data']['status'] == 0:
                        print '\033[32;1mHOST[%s] Servcie[%s] data valid\033[0m'%(ip,service_name)
                        print service_name,s_data['data']
                        #将插件数据中的几个关健值取出来,由于循环过多，所以定义service_item_handle来进行解藕
                        for item_key,val_dic in service_instance.triggers.items():
                            service_item_handle(main_ins,item_key,val_dic,s_data)
                    else:
                        print '\033[32;1mHOST[%s] Servcie[%s] plugin error\033[0m'%(ip,service_name)
                        
                else:# 数据过期
                    expired_time = time.time() - time_stamp - service_instance.interval
                    print '\033[31;1mHOST[%s] Servcie[%s] data expired [%s] secs\033[0m'%(ip,service_name,expired_time)
            else:
                print '\033[31;1m No data found in redis for service [%s] host[%s]\033[0m'%(service_name,ip)

def service_item_handle(main_ins,item_key,val_dic,client_service_data):
    print '==>',item_key,client_service_data['data'][item_key]
    #根据service的triger里的key,取出插件实际运行的值
    current_value = client_service_data['data'][item_key]
    warning_value = val_dic['warning']
    critical_value = val_dic['critical']
    oper = val_dic['operator']
    oper_func = getattr(operator,oper)
    print type(current_value)
    
    if val_dic['data_type'] is float:
        current_value = float(current_value)
        warning_res = oper_func(current_value,warning_value)
        critical_res = oper_func(current_value,critical_value)
        if critical_res :
            print '\033[41;1mCRITICAL:\033[0mHOST[%s] service[%s] 阀值 [%s] 当前值[%s]'%(client_service_data['host_ip'],client_service_data['service'],critical_value,current_value)
        elif warning_res :
            print '\033[43;1mWARNING:\033[0mHOST[%s] service[%s] 阀值 [%s] 当前值[%s]'%(client_service_data['host_ip'],client_service_data['service'],warning_value,current_value) 
        else:
            print '\033[42;1mNORMAL:\033[0mHOST[%s] service[%s] 阀值 [%s] 当前值[%s]'%(client_service_data['host_ip'],client_service_data['service'],warning_value,current_value) 
            
    
    
    